package me.flyray.bsin.server.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.*;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.IndexSettings;
import com.alibaba.cloud.ai.model.RerankModel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import me.flyray.bsin.domain.entity.KnowledgeBaseFile;
import me.flyray.bsin.facade.service.KnowledgeBaseFileService;
import me.flyray.bsin.server.biz.DocumentVectorBiz;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shenyu.client.apache.dubbo.annotation.ShenyuDubboService;
import org.apache.shenyu.client.apidocs.annotations.ApiDoc;
import org.apache.shenyu.client.dubbo.common.annotation.ShenyuDubboClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentReader;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.resolution.ToolCallbackResolver;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.elasticsearch.autoconfigure.ElasticsearchVectorStoreProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@ShenyuDubboService(value = "/knowledgeBaseFile/",  timeout = 60000)
public class KnowledgeBaseFileServiceImpl implements KnowledgeBaseFileService {

    private final VectorStore vectorStore;

    @Value("classpath:/prompts/system-qa.st")
    private Resource systemResource;
    @Value("classpath:/data/spring_ai_alibaba_quickstart.pdf")
    private Resource springAiResource;

    @Autowired
    private DocumentVectorBiz documentVectorBiz;

    public KnowledgeBaseFileServiceImpl(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }


    /**
     * 1、根据url下载文件
     * 2、解析文件
     * @param requestMap
     */
    @ApiDoc(desc = "importFile")
    @ShenyuDubboClient("/importFile")
    @Override
    public void importFile(Map<String, Object> requestMap) {

        String fileUrl = MapUtils.getString(requestMap, "fileUrl");
        String fileName = MapUtils.getString(requestMap, "name");
        String fileType = MapUtils.getString(requestMap, "fileType");
        String description = MapUtils.getString(requestMap, "description");
        String segmentMethod = MapUtils.getString(requestMap, "segmentMethod");
        String type = MapUtils.getString(requestMap, "type");
        
        // 构建文档元数据
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("fileName", fileName);
        metadata.put("fileType", fileType);
        metadata.put("fileUri", fileUrl);
        metadata.put("description", description);
        metadata.put("segmentMethod", segmentMethod);
        metadata.put("type", type);
        metadata.put("importTime", System.currentTimeMillis());
        metadata.put("status", "processing");
        
        // 处理文档并获取分割后的文档列表
        List<Document> documents = documentVectorBiz.processDocumentFromUrl(fileUrl, metadata);
        
        log.info("{} documents processed from file: {}", documents.size(), fileName);

        // 创建索引（如果不存在）
        documentVectorBiz.createIndexIfNotExists();
        
        // 添加文档到向量存储
        this.vectorStore.add(documents);
        
        log.info("{} documents added to vector store successfully", documents.size());
    }

    @ShenyuDubboClient("/addText")
    @Override
    public void addText(Map<String, Object> requestMap) {
        String text = MapUtils.getString(requestMap, "text");
        String title = MapUtils.getString(requestMap, "title", "手动输入文本"); // 默认标题
        String description = MapUtils.getString(requestMap, "description", "手动输入的文本内容");
        String type = MapUtils.getString(requestMap, "type", "2"); // 文本类型，区别于文件类型
        
        // 构建文本元数据
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("title", title);
        metadata.put("description", description);
        metadata.put("type", type);
        metadata.put("textLength", text != null ? text.length() : 0);
        metadata.put("importTime", System.currentTimeMillis());
        metadata.put("inputMethod", "manual"); // 标识为手动输入
        
        log.info("Processing text input: title={}, length={}", title, text != null ? text.length() : 0);
        
        // 创建索引（如果不存在）
        documentVectorBiz.createIndexIfNotExists();
        
        // 创建文档
        List<Document> documents = List.of(new Document(text, metadata));
        
        // 添加文档到向量存储
        this.vectorStore.add(documents);
        
        log.info("Text document added to vector store successfully: {}", title);
    }

    @ApiDoc(desc = "retrieval")
    @ShenyuDubboClient("/retrieval")
    @Override
    public Map<String, Object> retrieval(Map<String, Object> requestMap) {
        String message = MapUtils.getString(requestMap, "message");
        // Retrieve documents similar to a query
        List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder()
                .query(message)
                .topK(1)
                .build());
        System.out.println(results.size());
        for (Document documents : results){
            System.out.println(documents.getText());
        }
        Map resultMap  = new HashMap<>();
        resultMap.put("answer", results.get(0).getText());
        return resultMap;
    }

    @ApiDoc(desc = "delete")
    @ShenyuDubboClient("/delete")
    @Override
    public void delete(Map<String, Object> requestMap) {

    }

    @ApiDoc(desc = "edit")
    @ShenyuDubboClient("/edit")
    @Override
    public void edit(Map<String, Object> requestMap) {

    }

    @ApiDoc(desc = "getDetail")
    @ShenyuDubboClient("/getDetail")
    @Override
    public KnowledgeBaseFile getDetail(Map<String, Object> requestMap) throws Exception {
        return null;
    }

    @ApiDoc(desc = "getPageList")
    @ShenyuDubboClient("/getPageList")
    @Override
    public IPage<?> getPageList(Map<String, Object> requestMap) {
        return null;
    }

    @ApiDoc(desc = "getList")
    @ShenyuDubboClient("/getList")
    @Override
    public List<KnowledgeBaseFile> getList(Map<String, Object> requestMap) {
        return null;
    }



}
